axios.defaults.baseURL = 'http://ajax-base-api-t.itheima.net'
const list = document.querySelector('#tb')
const form = document.querySelector('#bookForm')
const btn = document.querySelector('#btnAdd')
const btnSelect = document.querySelector('#btnSelect');
async function renderData() {
 const { data: {data:res} }=await axios.get('/api/getbooks')
    list.innerHTML = res
      .map((item) => {
        return `<tr>
      <td>${item.id}</td>
      <td>${item.bookname}</td>
      <td>${item.author}</td>
      <td>${item.publisher}</td>
      <td><a href="javascript:;" class="del" data-id='${item.id}'>删除</a></td>
    </tr>`
      })
      .join('')
}
renderData()
form.addEventListener('submit',async function (e) {
  e.preventDefault()
  const data = serialize(this, { hash: true })
  const { data: res } = await axios.post('/api/addbook', data)
  alert(res.msg)
  if (res.status !== 201) return
  this.reset()
  renderData()
})
list.addEventListener('click', function (e) {
  if (e.target.tagName === 'A') {
    let delid = e.target.dataset.id
    console.log(typeof delid)
    axios.get(`/api/delbook?id=${delid}`)
    renderData()
  }
})
btnSelect.addEventListener('click',async function () {
  const data = serialize(form, { hash: true })
  const { data: { data: res } } = await axios.get('/api/getbooks', { params: data })
  list.innerHTML = res.map((item) => {
   return `<tr>
             <td>${item.id}</td>
             <td>${item.bookname}</td>
             <td>${item.author}</td>
             <td>${item.publisher}</td>
             <td><a href="javascript:;" class="del" data-id='${item.id}'>删除</a></td>
           </tr>`
        }).join('')
})
